package cn.yanxiaohui.service.web.pattern.observer;

import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 被观察的实现类（虫洞新闻）
 */
public class CDNews implements Observerable {

    private List<Observer> observerList;

    private String message;

    public CDNews(){
        observerList = new ArrayList<Observer>();
    }

    @Override
    public void subscribe(Observer observer) {
        if(observerList != null){
            observerList.add(observer);
        }
    }

    @Override
    public void remove(Observer observer) {
        if(!CollectionUtils.isEmpty(observerList)){
            observerList.remove(observer);
        }
    }

    @Override
    public void notifyObserver() {
        for (Observer observer : observerList) {
            observer.receive(message);
        }
    }

    /**
     * 发布订阅信息
     * @param message
     */
    public void sendMessage(String message){
        this.message = message;
        System.out.println("虫洞新闻发布新的信息：" + message);
        notifyObserver();
    }
}
